/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.gov.ana.dao;

import br.gov.ana.service.MedicaoWS;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author lucas.nunes
 */
public class MedHidrometeorologicaDAO {

    public List<MedicaoWS> getListaEstacoesPorEstacao(String codigoFlu, int ano, int variavel) throws Exception {

        EntityManagerFactory factory = Persistence.createEntityManagerFactory("resolucaowsPU");
        EntityManager entityManager = factory.createEntityManager();

        Query q = entityManager.createQuery("SELECT new  br.gov.ana.service.MedicaoWS "
                + "(mh.mdhDt, mh.mdhVr ) FROM MedHidrometeorologica mh "
                + "LEFT JOIN mh.mdhCvhId cv "
                + "LEFT JOIN cv.cvhVarId va "
                + "LEFT JOIN cv.cvhEstId es "
                + "LEFT JOIN es.orgaoEstacaoLista oe "
                + "WHERE es.estCdFlu = :codigoFlu AND va.varId = :variavel AND oe.oesOrgId.orgId IS NOT NULL AND mh.mdhNuNotafinalmetafiltro IS NOT NULL AND mh.mdhDt between :dataInicial AND :dataFinal "
                + "GROUP BY mh.mdhDt, mh.mdhVr "
                + "ORDER BY mh.mdhDt DESC");

        q.setParameter("codigoFlu", codigoFlu);
        q.setParameter("variavel", getVariavel(variavel));
        q.setParameter("dataInicial", getDataInicial(ano));
        q.setParameter("dataFinal", getDataFinal(ano));
        return q.getResultList();
    }

    public Date getDataInicial(int ano) {
        Calendar dataInicial = Calendar.getInstance();
        dataInicial.set(ano, 0, 1);
        return dataInicial.getTime();
    }

    public Date getDataFinal(int ano) {
        Calendar dataFinal = Calendar.getInstance();
        dataFinal.set(ano, 11, 31);
        return dataFinal.getTime();
    }

    public int getVariavel(int variavel) {
        int retorno;
        switch (variavel) {
            case 1:
                retorno = 1;
                break;
            case 2:
                retorno = 3;
                break;
            case 3:
                retorno = 4;
                break;
            default:
                retorno = 1;
                break;
        }
        return retorno;
    }
}
